<script lang="ts" setup>
import { ref, reactive, onMounted, h, watch } from 'vue';
import { 
  Card, Table, Button, Input, Space, Form, Select, DatePicker, 
  message, Tag, Tooltip 
} from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { 
  getTransactionListApi, 
  getTransactionSubTypesApi,
  type TransactionApi 
} from '#/api/core/transaction';

interface TransactionRecord {
  id: string;
  transaction_id: string;
  transaction_number: string;
  tenant_id: number;
  type: 'income' | 'expense';
  type_display: string;
  sub_type: string;
  sub_type_display: string;
  amount: number;
  balance_after: number;
  landing_company: string;
  status: 'pending' | 'processing' | 'completed' | 'failed' | 'cancelled';
  status_display: string;
  summary: string;
  description?: string;
  transaction_time: string;
  created_at: string;
}

interface PaginationData {
  current: number;
  pageSize: number;
  total: number;
  showSizeChanger: boolean;
  showQuickJumper: boolean;
  pageSizeOptions: string[];
  showTotal: (total: number, range: [number, number]) => string;
}

interface SubTypeOption {
  value: string;
  label: string;
}

// 响应式数据
const loading = ref(false);
const dataSource = ref<TransactionRecord[]>([]);

// 搜索表单
const searchForm = reactive({
  transaction_id: '',
  type: undefined as string | undefined,
  sub_type: undefined as string | undefined,
  start_date: undefined as string | undefined,
  end_date: undefined as string | undefined,
});

// 分页数据
const pagination = reactive<PaginationData>({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '15', '20', '50'],
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
});

// 类型选项
const typeOptions = [
  { value: 'income', label: '入账' },
  { value: 'expense', label: '出账' }
];

// 子类型选项
const subTypeOptions = ref<SubTypeOption[]>([]);
const subTypeLoading = ref(false);

// 状态选项
const statusOptions = [
  { value: 'pending', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' },
  { value: 'failed', label: '失败' },
  { value: 'cancelled', label: '已取消' }
];

// 表格列定义
const columns: TableColumnsType<TransactionRecord> = [
  {
    title: '账单ID',
    dataIndex: 'transaction_id',
    key: 'transaction_id',
    width: 130,
    ellipsis: true,
    customRender: ({ record }) => {
      return h(Tooltip, 
        { title: `完整ID: ${record.id}` }, 
        () => record.transaction_id
      );
    }
  },
  {
    title: '类型',
    dataIndex: 'type_display',
    key: 'type',
    width: 80,
    customRender: ({ record }) => {
      const colorMap = {
        'income': 'success',
        'expense': 'error'
      };
      return h(Tag, 
        { color: colorMap[record.type] }, 
        () => record.type_display
      );
    }
  },
  {
    title: '子类型',
    dataIndex: 'sub_type_display',
    key: 'sub_type',
    width: 100,
    ellipsis: true,
  },
  {
    title: '交易金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 120,
    align: 'right',
    customRender: ({ record }) => {
      const prefix = record.type === 'income' ? '+' : '-';
      const color = record.type === 'income' ? '#52c41a' : '#ff4d4f';
      return h('span', 
        { style: { color, fontWeight: 'bold' } }, 
        `${prefix}¥${Number(record.amount).toLocaleString()}`
      );
    },
  },
  {
    title: '交易后余额',
    dataIndex: 'balance_after',
    key: 'balance_after',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ record }) => {
      const statusColorMap: Record<string, string> = {
        'pending': 'default',
        'processing': 'processing',
        'completed': 'success',
        'failed': 'error',
        'cancelled': 'default'
      };
      
      return h(Tag, 
        { color: statusColorMap[record.status] }, 
        () => record.status_display
      );
    },
  },
  {
    title: '交易落地公司',
    dataIndex: 'landing_company',
    key: 'landing_company',
    width: 150,
    ellipsis: true,
  },
  {
    title: '交易时间',
    dataIndex: 'transaction_time',
    key: 'transaction_time',
    width: 160,
    customRender: ({ text }) => {
      return new Date(text).toLocaleString('zh-CN');
    },
  },
  {
    title: '交易摘要',
    dataIndex: 'summary',
    key: 'summary',
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => {
      return text ? h(Tooltip, { title: text }, () => text) : '-';
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 80,
    fixed: 'right',
    customRender: ({ record }) => {
      return h(Button, { 
        type: 'link', 
        size: 'small',
        onClick: () => handleViewDetail(record.id)
      }, '查看');
    },
  },
];

// 监听类型变化，更新子类型选项
watch(() => searchForm.type, async (newType) => {
  if (newType) {
    await fetchSubTypes(newType as 'income' | 'expense');
  } else {
    await fetchSubTypes();
  }
  // 重置子类型选择
  searchForm.sub_type = undefined;
}, { immediate: false });

// 获取列表数据
const fetchData = async () => {
  try {
    loading.value = true;
    
    const params = {
      page: pagination.current,
      per_page: pagination.pageSize,
      transaction_id: searchForm.transaction_id.trim() || undefined,
      type: searchForm.type as 'income' | 'expense' | undefined,
      sub_type: searchForm.sub_type,
      start_date: searchForm.start_date,
      end_date: searchForm.end_date,
    };
    
    console.log('📤 发送请求参数:', params);
    
    const response = await getTransactionListApi(params);
    console.log('📥 API响应:', response);
    
    dataSource.value = response.data || [];
    pagination.total = response.total || 0;
    pagination.current = response.current_page || 1;

    console.log('✅ 数据更新成功:', {
      count: dataSource.value.length,
      total: pagination.total,
      current: pagination.current
    });
  } catch (error) {
    console.error('❌ 请求失败:', error);
    message.error('网络请求失败，请稍后重试');
    dataSource.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 获取子类型选项
const fetchSubTypes = async (type?: 'income' | 'expense') => {
  try {
    subTypeLoading.value = true;
    const response = await getTransactionSubTypesApi(type);
    
    subTypeOptions.value = response || [];
  } catch (error) {
    console.error('获取子类型失败:', error);
    subTypeOptions.value = [];
  } finally {
    subTypeLoading.value = false;
  }
};

// 搜索操作
const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

// 重置搜索条件
const handleReset = () => {
  searchForm.transaction_id = '';
  searchForm.type = undefined;
  searchForm.sub_type = undefined;
  searchForm.start_date = undefined;
  searchForm.end_date = undefined;
  pagination.current = 1;
  fetchData();
};

// 导出数据（占位）
const handleExport = () => {
  message.info('导出功能开发中...');
};

// 查看详情
const handleViewDetail = (id: string) => {
  message.info(`查看详情 ID: ${id}，功能开发中...`);
};

// 分页变化处理
const handleTableChange = (paginationParams: any) => {
  pagination.current = paginationParams.current;
  pagination.pageSize = paginationParams.pageSize;
  fetchData();
};

// 时间范围选择处理
const handleDateRangeChange = (dates: any, dateStrings: string[]) => {
  searchForm.start_date = dateStrings[0] || undefined;
  searchForm.end_date = dateStrings[1] || undefined;
};

// 组件挂载时加载数据
onMounted(() => {
  fetchSubTypes(); // 加载所有子类型
  fetchData();
});
</script>

<template>
  <div class="p-5">
    <Card>
      <!-- 搜索区域 -->
      <div class="mb-4">
        <Form layout="inline" :model="searchForm">
          <Form.Item label="账单ID" name="transaction_id">
            <Input
              v-model:value="searchForm.transaction_id"
              placeholder="请输入账单ID"
              style="width: 160px"
              allowClear
              @pressEnter="handleSearch"
            />
          </Form.Item>
          
          <Form.Item label="类型" name="type">
            <Select
              v-model:value="searchForm.type"
              placeholder="请选择类型"
              style="width: 120px"
              allowClear
            >
              <Select.Option 
                v-for="type in typeOptions" 
                :key="type.value" 
                :value="type.value"
              >
                {{ type.label }}
              </Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item label="子类型" name="sub_type">
            <Select
              v-model:value="searchForm.sub_type"
              placeholder="请选择子类型"
              style="width: 120px"
              allowClear
              :loading="subTypeLoading"
              :disabled="!searchForm.type"
            >
              <Select.Option 
                v-for="subType in subTypeOptions" 
                :key="subType.value" 
                :value="subType.value"
              >
                {{ subType.label }}
              </Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item label="交易时间" name="date_range">
            <DatePicker.RangePicker
              style="width: 240px"
              @change="handleDateRangeChange"
            />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                @click="handleSearch"
                :loading="loading"
              >
                查询
              </Button>
              <Button @click="handleReset">
                重置
              </Button>
              <Button @click="handleExport">
                导出数据
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
      
      <!-- 数据表格 -->
      <Table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        :scroll="{ x: 1400 }"
        @change="handleTableChange"
      />
    </Card>
  </div>
</template>

<style scoped>
.ant-table-tbody > tr > td {
  padding: 12px 8px;
}

.ant-form-item {
  margin-bottom: 16px;
}
</style>